import React, { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import * as echarts from '../../ec-canvas/echarts';
import { Failure, Clock, Success } from '@nutui/icons-react-taro';
import { taskApi } from '../../services/taskApi';
import { useInfoStore } from '../../store/useInfoStore';
import Taro from '@tarojs/taro';

// 图表初始化函数
function initChart(canvas, width, height) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        max: 100
      }
    ],
    series: [
      {
        name: '任务完成率',
        type: 'bar',
        barWidth: '60%',
        data: [],
        itemStyle: {
          color: '#3b82f6'
        }
      },
      {
        name: '平均完成率',
        type: 'line',
        data: [],
        symbol: 'none',
        lineStyle: {
          color: '#10b981',
          width: 2
        }
      }
    ]
  };

  chart.setOption(option);
  return chart;
}

const StudentDashboard = () => {
  const [taskList, setTaskList] = useState([]);
  const [showAllTasks, setShowAllTasks] = useState(false);
  const [dailyTaskProgressReport, setDailyTaskProgressReport] = useState({});
  const [chartInstance, setChartInstance] = useState(null);
  const ec = {
    onInit: (canvas, width, height) => {
      const chart = initChart(canvas, width, height);
      setChartInstance(chart);
      return chart;
    }
  };

  const userInfo = useInfoStore(state => state.info);  

  const getTaskListByUser = async () => {
    try {
      if (!userInfo?.id) {
        return;
      }
      const res = await taskApi.getTaskListByUser({ user_id: userInfo?.id });
      const res2 = await taskApi.getDailyTaskProgressReport();
      setTaskList(res || []);
      setDailyTaskProgressReport(res2 || {});
    } catch (error) {
      console.log('获取任务列表失败', error);
    }
  }

  useEffect(() => {
    getTaskListByUser();
  }, [userInfo]);

  // 当dailyTaskProgressReport数据变化时更新图表
  useEffect(() => {
    if (chartInstance && dailyTaskProgressReport?.basic_scores && dailyTaskProgressReport?.avg_scores) {
      const days = dailyTaskProgressReport.basic_scores.map(item => item.day);
      const basicScores = dailyTaskProgressReport.basic_scores.map(item => item.score);
      const avgScores = dailyTaskProgressReport.avg_scores.map(item => item.score);

      chartInstance.setOption({
        xAxis: [{
          data: days
        }],
        series: [
          {
            name: '任务完成率',
            data: basicScores
          },
          {
            name: '平均完成率',
            data: avgScores
          }
        ]
      });
    }
  }, [dailyTaskProgressReport, chartInstance]);

  // 获取要显示的任务列表
  const getDisplayTaskList = () => {
    return showAllTasks ? taskList : taskList.slice(0, 3);
  };

  // 获取任务状态对应的图标和颜色
  const getTaskStatusInfo = (status) => {
    switch (status) {
      case '已结束':
        return {
          icon: <Success size="20" color="#10b981" />,
          iconClass: 'completed',
          badgeClass: 'completed'
        };
      case '未开始':
        return {
          icon: <Failure size="20" color="#64748b"  style={{fontWeight: 'bold'}} />,
          iconClass: 'not-started',
          badgeClass: 'not-started'
        };
      case '进行中':
        return {
          icon: <Clock size="20" color="#5c9dff"  style={{fontWeight: 'bold'}} />,
          iconClass: 'in-progress',
          badgeClass: 'in-progress'
        };
      case '已完成':
        return {
          icon: <Success size="20" color="#10b981" />,
          iconClass: 'completed',
          badgeClass: 'completed'
        };
      default:
        return {
          icon: <Failure size="20" color="#ef4444" />,
          iconClass: 'overdue',
          badgeClass: 'overdue'
        };
    }
  };

  const navigateToTaskDetail = (task_id) => {
    Taro.navigateTo({
      url: `/package-task/pages/detail/index?task_id=${task_id}&SessionId=${userInfo?.id}`,
      fail: (error) => {
        console.error('跳转失败:', error);
        Taro.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  }

  return (
    <View className="student-dashboard">
      <View className="task-card">
        <View className="card-header">
          <Text className="card-title">本周期任务完成情况</Text>
          <Text className="card-action">查看详情</Text>
        </View>

        <View className="stats-container">
          <View className="stat-card">
            <Text className="stat-label">完成任务</Text>
            <View className="stat-value-container">
              <Text className="stat-value">{dailyTaskProgressReport?.completed_tasks || 0}</Text>
              <Text className="stat-change">+1</Text>
            </View>
          </View>
          <View className="stat-card">
            <Text className="stat-label">总任务</Text>
            <View className="stat-value-container">
              <Text className="stat-value">{dailyTaskProgressReport?.total_tasks || 0}</Text>
            </View>
          </View>
          <View className="stat-card">
            <Text className="stat-label">完成率</Text>
            <View className="stat-value-container">
              <Text className="stat-value">{dailyTaskProgressReport?.completion_rate || 0}%</Text>
              <Text className="stat-change">↑</Text>
            </View>
          </View>
        </View>

        <View className="progress-bar-container">
          <View className="progress-bar" style={{ width: `${dailyTaskProgressReport?.completion_rate || 0}%` }}></View>
        </View>
        <Text className="progress-text">距离本周期结束还有 {dailyTaskProgressReport?.days_remaining || 0} 天</Text>
      </View>

      <View className="chart-card">
        <View className="chart-header">
          <Text className="chart-title">学习进度趋势</Text>
          <View className="tab-group">
            <Text className="tab active">周</Text>
            <Text className="tab inactive">月</Text>
          </View>
        </View>

        <View className="chart-container">
          <ec-canvas force-use-old-canvas="true" id="progressChartDom" canvas-id="progressChart" ec={ec}></ec-canvas>
        </View>
      </View>

      <View className="history-card">
        <View className="history-header">
          <View className="header-content">
            <Text className="header-title">全部任务概览</Text>
            <Text 
              className="header-action" 
              onClick={() => setShowAllTasks(!showAllTasks)}
            >
              {showAllTasks ? '收起' :  taskList.length > 3 ? '查看全部' : ''}
            </Text>
          </View>
        </View>

        {getDisplayTaskList().map((task, index) => {
          const statusInfo = getTaskStatusInfo(task.status);
          return (
            <View 
              className="history-item" 
              key={task.task_id}
              onClick={() => {
                navigateToTaskDetail(task.task_id)
              }}
            >
              <View className={`item-icon ${statusInfo.iconClass}`}>
                {statusInfo.icon}
              </View>
              <View className="item-content">
                <Text className="item-title">{task.progress.basic_task_requirements}</Text>
                <Text className="item-subtitle">
                  {task?.start_time?.split(' ')[0]} - {task?.end_time?.split(' ')[0]}
                </Text>
              </View>
              <View className="item-status">
                <Text className={`status-badge ${statusInfo.badgeClass}`}>{task.status}</Text>
              </View>
            </View>
          );
        })}

        {!showAllTasks && taskList.length > 3 && (
          <View className="show-more-hint">
            <Text className="hint-text">还有 {taskList.length - 3} 条任务</Text>
          </View>
        )}
      </View>
    </View>
  );
};

export default StudentDashboard;
